#!/usr/bin/perl

#use warnings;
use Card;
use DefaultDeck;

$deck = new DefaultDeck();

sub main {
	return play();
}

sub value {
	$name = $_[0];
	$value = substr $name, 1;
	if ($value eq "A") 
	{
		return 1;
	} 
	else 
	{
		if ($value eq "J") 
		{  
			return 11;
		}
		else 
		{
			if ($value eq "Q") 
			{
				return 12;
			}
			else 
			{
				if ($value eq "K") 
				{
					return 13;
				}
				else 
				{
					return $value;
				}
			}
		}
	}
}

sub play {
	$currentCard = "";
	$nextCard = "";
	$currentValue = 0;
	$nextValue = 0;
	$gameScore = 0;
	$guess = 0;
	
	$currentCard = $deck->draw()->getname();
	$currentValue = value($currentCard);
	
	print "The first card is ";
	print $currentCard;
	print " with value ";
	print $currentValue."\n";
	
	while ($deck->size()) { # Loop ends when there are no more cards or the user is wrong.
		print "Do you think the next card will be lower (0) or higher (1)?\n";
		$guess = <STDIN>;
		
		while ($guess*$guess != $guess) 
		{
			print "Please respond with 0 or 1.\n";
			$guess = <STDIN>;
		}
		
		$nextCard = $deck->draw()->getname();
		$nextValue = value($nextCard);
		print "The next card is ";
		print $nextCard;
		print " with value ";
		print $nextValue."\n";
		
		if ($nextValue == $currentValue) 
		{
			print "The values are the same. You lose."."\n";
			last;
		} 
		else {
			if ($nextValue > $currentValue) 
			{
				if ($guess == 1) 
				{
					print "Your prediction was correct."."\n";
					$gameScore++;
				} 
				else 
				{
					print "Your prediction was incorrect."."\n";
					last;
				}
			} 
			else 
			{
				if ($guess == 0) 
				{
					print "Your prediction was correct."."\n";
					$gameScore++;
				} 
				else 
				{
					print "Your prediction was incorrect."."\n";
					last;
				}
			}
		}
		$currentCard = $nextCard;
		$currentValue = $nextValue;
		print "The card is ";
		print $currentCard;
		print " with value ";
		print $currentValue."\n";
	} 
	print "The game is over."."\n";
	print "You made ";
	print $gameScore;
	print " correct predictions."."\n";
	return $gameScore;
}
print main()."\n";